package com.svs.web.controller.system;

import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.svs.common.annotation.Log;
import com.svs.common.base.AjaxResult;
import com.svs.common.constant.UserConstants;
import com.svs.common.enums.BusinessType;
import com.svs.common.utils.ExcelUtil;
import com.svs.common.utils.RSAEncryptUtils;
import com.svs.common.utils.StringUtils;
import com.svs.framework.shiro.service.SysPasswordService;
import com.svs.framework.shiro.util.ShiroUtils;
import com.svs.framework.web.BackendController;
import com.svs.framework.web.page.TableDataInfo;
import com.svs.system.cache.SysAreaCache;
import com.svs.system.domain.AreaNode;
import com.svs.system.domain.SysUser;
import com.svs.system.service.SysPostService;
import com.svs.system.service.SysRoleService;
import com.svs.system.service.SysUserService;

/**
 * 用户信息
 * 
 * @author dujianqiao
 */
@Controller
@RequestMapping("/system/user")
public class SysUserController extends BackendController {
	private String prefix = "system/user";

	@Autowired
	private SysUserService userService;

	@Autowired
	private SysRoleService roleService;

	@Autowired
	private SysPostService postService;

	@Autowired
	private SysPasswordService passwordService;

	@RequiresPermissions("system:user:view")
	@GetMapping()
	public String user() {
		return prefix + "/user";
	}

	/**
	 * 新增操作用户
	 * 
	 * @return
	 */
	@GetMapping("/addHandleUser")
	public String addHandleUser() {
		return prefix + "/addHandleUser";
	}

	@RequiresPermissions("system:user:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(SysUser user) {
		startPage();
		user.setNotUserType(UserConstants.USER_TYPE_EP);//不查询企业用户
		List<SysUser> list = userService.selectAllList(user);
		return getDataTable(list);
	}

	@Log(title = "用户管理", businessType = BusinessType.EXPORT)
	@RequiresPermissions("system:user:export")
	@PostMapping("/export")
	@ResponseBody
	public AjaxResult export(SysUser user) {
		List<SysUser> list = userService.selectAllList(user);
		ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
		return util.exportExcel(list, "user");
	}

	/**
	 * 新增用户
	 */
	@GetMapping("/add")
	public String add(ModelMap mmap) {
		mmap.put("roles", roleService.selectRoleAll());
		mmap.put("posts", postService.selectPostAll());
		List<AreaNode> areaNodeList = SysAreaCache.getCache().getFirstArea();
		mmap.addAttribute("areaNodeList", areaNodeList);
		//只查询审核通过的企业
//		EnterpriseInfo info = new EnterpriseInfo();
//		info.setState(EnterpriseInfoConstants.ENTER_CHECK_STATE_CITY_PASS);
//		mmap.put("enterpriseList", enterpriseInfoService.selectAllList(info));
		return prefix + "/add";
	}

	/**
	 * 新增保存用户
	 */
	@RequiresPermissions("system:user:add")
	@Log(title = "用户管理", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@Transactional(rollbackFor = Exception.class)
	@ResponseBody
	public AjaxResult addSave(SysUser user) {
		if (StringUtils.isNotNull(user.getUserId()) && SysUser.isAdmin(user.getUserId())) {
			return error("不允许修改超级管理员用户");
		}
		user.setSalt(ShiroUtils.randomSalt());
		user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
		user.setCreateBy(ShiroUtils.getLoginName());
		return toAjax(userService.insertSelective(user));
	}

	/**
	 * 修改用户
	 */
	@GetMapping("/edit/{userId}")
	public String edit(@PathVariable("userId") Long userId, ModelMap mmap) {
		mmap.put("user", userService.selectByPrimaryKey(userId));
		mmap.put("roles", roleService.selectRolesByUserId(userId));
		mmap.put("posts", postService.selectPostsByUserId(userId));
		List<AreaNode> areaNodeList = SysAreaCache.getCache().getFirstArea();
		mmap.put("cityCode", ShiroUtils.getSysUser().getCityCode());
		mmap.put("city", ShiroUtils.getSysUser().getCity());
		mmap.addAttribute("areaNodeList", areaNodeList);
		return prefix + "/edit";
	}

	/**
	 * 修改保存用户
	 */
	@RequiresPermissions("system:user:edit")
	@Log(title = "用户管理", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@Transactional(rollbackFor = Exception.class)
	@ResponseBody
	public AjaxResult editSave(SysUser user) {
		if (StringUtils.isNotNull(user.getUserId()) && SysUser.isAdmin(user.getUserId())) {
			return error("不允许修改超级管理员用户");
		}
		user.setUpdateBy(ShiroUtils.getLoginName());
		return toAjax(userService.updateByPrimaryKeySelective(user));
	}

	@RequiresPermissions("system:user:resetPwd")
	@Log(title = "重置密码", businessType = BusinessType.UPDATE)
	@GetMapping("/resetPwd/{userId}")
	public String resetPwd(@PathVariable("userId") Long userId, ModelMap mmap) {
		mmap.put("user", userService.selectByPrimaryKey(userId));
		return prefix + "/resetPwd";
	}

	@RequiresPermissions("system:user:resetPwd")
	@Log(title = "重置密码", businessType = BusinessType.UPDATE)
	@PostMapping("/resetPwd")
	@ResponseBody
	public AjaxResult resetPwdSave(SysUser user) {
		user.setSalt(ShiroUtils.randomSalt());
		user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
		return toAjax(userService.resetUserPwd(user));
	}

	@RequiresPermissions("system:user:resetPwd")
	@Log(title = "重置密码", businessType = BusinessType.UPDATE)
	@PostMapping("/resetPwdAll")
	@ResponseBody
	public AjaxResult resetPwdAll() {
		List<SysUser> userList = userService.selectAllList(new SysUser());
		for (SysUser user : userList) {
			SysUser entity = new SysUser() ;
			entity.setLoginName(user.getLoginName());
			
			entity.setUserId(user.getUserId());
			entity.setPassword("123456");
			entity.setSalt(ShiroUtils.randomSalt());
			entity.setPassword(passwordService.encryptPassword(entity.getLoginName(), entity.getPassword(), entity.getSalt()));
			userService.resetUserPwd(entity);
		}
		return success();
	}

	@RequiresPermissions("system:user:remove")
	@Log(title = "用户管理", businessType = BusinessType.DELETE)
	@PostMapping("/remove")
	@ResponseBody
	public AjaxResult remove(String ids) {
		try {
			return toAjax(userService.deleteUserByIds(ids));
		} catch (Exception e) {
			return error(e.getMessage());
		}
	}

	/**
	 * 校验用户名
	 */
	@PostMapping("/checkLoginNameUnique")
	@ResponseBody
	public String checkLoginNameUnique(SysUser user) {
		return userService.checkLoginNameUnique(user.getLoginName());
	}

	/**
	 * 校验手机号码
	 */
	@PostMapping("/checkPhoneUnique")
	@ResponseBody
	public String checkPhoneUnique(SysUser user) {
		return userService.checkPhoneUnique(user);
	}

	/**
	 * 校验email邮箱
	 */
	@PostMapping("/checkEmailUnique")
	@ResponseBody
	public String checkEmailUnique(SysUser user) {
		return userService.checkEmailUnique(user);
	}
	
	@GetMapping("/other")
	public String toOther(ModelMap mmap) {
		String a = ShiroUtils.getLoginName();
		String b = "";
		try {
			b = RSAEncryptUtils.encrypt(a);
		} catch (Exception e) {
		}
		mmap.put("a", a);
		mmap.put("b", b);
		return prefix + "/toOther";
	}
}